package com.wang.hot_deploy;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class HotDeployDemo {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        ClassLoader cl = new LocalClassLoader();
        Scanner scanner = new Scanner(System.in);
        String clzName = null;
        while (!(clzName = scanner.next()).equals("end")) {
            Class clz = cl.loadClass(clzName);
            Count count = (Count) clz.newInstance();
            System.out.println(count.count(1, 1));
        }
    }

    public static class LocalClassLoader extends ClassLoader {
        @Override
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (!name.startsWith("CountWith")) return super.loadClass(name);
            String filepath = "C:\\Users\\Administrator\\Desktop\\clz\\" + name + ".class";
            try (InputStream is = new FileInputStream(filepath)) {
                int size = is.available();
                byte[] bs = new byte[size];

                int count = 0;
                while ((count = is.read(bs, count, size - count)) != -1) {
                }

                return defineClass(null, bs, 0, bs.length);
            } catch (IOException e) {
                e.printStackTrace();
                throw new ClassNotFoundException();
            }
        }
    }
}
